#include "android_env.h"
#include "android_lcd.h"

#define TEXT_SIZE 24

typedef struct _RECT {
    int x;
    int y;
    int width;
    int height;
} RECT;

void android_lcd_brush_screen(void)
{
    int detach = 0;
    jmethodID method = NULL;

    JNIEnv *env = initJavaCallbackMethod(&method, "ddi_lcd_brush_screen", "()V", &detach);
    if (env == NULL || method == NULL)
    {
        return;
    }

    (*env)->CallVoidMethod(env, mCallbackObj, method);
    detach_thread(detach);
}

void android_lcd_clear_rect(int x0, int x1, int y0, int y1)
{
    int detach = 0;
    jmethodID method = NULL;

    JNIEnv *env = initJavaCallbackMethod(&method, "ddi_lcd_clear_rect", "(IIII)V", &detach);
    if (env == NULL || method == NULL)
    {
        return;
    }

    (*env)->CallVoidMethod(env, mCallbackObj, method, x0, y0, x1, y1);
    detach_thread(detach);

    android_lcd_brush_screen();
}

void android_lcd_show_text(int x, int y, const char *text)
{
    int detach = 0;
    jmethodID method = NULL;
    jbyteArray byteArray = NULL;

    JNIEnv *env = initJavaCallbackMethod(&method, "ddi_lcd_show_text", "(II[B)V", &detach);
    if (env == NULL || method == NULL)
    {
        return;
    }

    byteArray = (*env)->NewByteArray(env, strlen(text));
    (*env)->SetByteArrayRegion(env, byteArray, 0, strlen(text), (jbyte *) text);
    (*env)->CallVoidMethod(env, mCallbackObj, method, x, y, byteArray);
    (*env)->DeleteLocalRef(env, byteArray);
    detach_thread(detach);
    android_lcd_brush_screen();
}

static void getLineRect(LINE line, RECT *rect)
{
    rect->width = 320;
    rect->height = 240 / 6;
    rect->x = 0;
    rect->y = (int) line * rect->height;
}

void android_lcd_clear_line(LINE line)
{
    RECT rect = {0};

    getLineRect(line, &rect);
    android_lcd_clear_rect(rect.x, rect.x + rect.width, rect.y, rect.y + rect.height);
}

void android_lcd_show_line(LINE line, const char *text)
{
    RECT rect = {0};

    getLineRect(line, &rect);

    android_lcd_show_text(rect.x, (rect.y + rect.height - TEXT_SIZE / 2), text);
}

void android_lcd_show_bitmap(int x, int y, int width, int height, const unsigned char *bitmap)
{
    int detach = 0;
    jmethodID method = NULL;
    jbyteArray byteArray = NULL;

    JNIEnv *env = initJavaCallbackMethod(&method, "ddi_lcd_show_picture", "(IIII[B)V", &detach);
    if (env == NULL || method == NULL)
    {
        return;
    }

    byteArray = chars_to_jbyteArray(env, bitmap, width * height * 2);

    (*env)->CallVoidMethod(env, mCallbackObj, method, x, y, x + width, y + height, byteArray);
    (*env)->DeleteLocalRef(env, byteArray);
    detach_thread(detach);
    android_lcd_brush_screen();
}

void android_lcd_clear_screen(void)
{
	android_lcd_clear_rect(0,319,0,239);
}
